package com.hitplane.manager 
{
	import com.hitplane.core.BaseDisplay;
	import com.hitplane.core.CheckCollision;
	import com.hitplane.debug.DebugTrace;
	import com.hitplane.interfaces.ICollisionAble;
	import com.hitplane.interfaces.IDisplayObject;
	import com.hitplane.interfaces.ITick;
	
	import flash.utils.getTimer;

	/**
	 * 碰撞检测
	 * 单例模式类
	 * @author 郑子华
	 */
	public class CheckCollisionManager extends CheckCollision implements ITick
	{
		private static var _instance:CheckCollisionManager = null;
		public function CheckCollisionManager(single:Single) 
		{
			
			if(single == null)
			{
				throw new Error("Can't create instance , Single is Null!");
			}
			_createTime = getTimer();
			_timeGap = 100;
		}
		/**
		 * 单例引用
		 */
		public static function get instance():CheckCollisionManager
		{
			if(_instance == null)
			{
				_instance = new CheckCollisionManager(new Single());
			}
			return _instance;
		}
		/* INTERFACE com.hitplane.interfaces.ITick */
		private var _timeGap:int;
		private var _executeTime:int;
		private var _createTime:int;
		public function get timeGap():int { return _timeGap; }
		
		public function set timeGap(value:int):void 
		{
			_timeGap = value;
		}
		
		public function get executeTime():int { return _executeTime; }
		
		public function set executeTime(value:int):void 
		{
			_executeTime = value;
		}
		
		public function get createTime():int { return _createTime; }
		
		public function set createTime(value:int):void 
		{
			_createTime = value;
		}
		/**
		 * @param	tickTime	getTimer()值
		 */
		public function updateForTick(tickTime:int):void {
			if(_createTime==0)return;
			var totalTime:int = (tickTime-_createTime) / timeGap;
			if (totalTime > _executeTime) {
				onTick();
				_executeTime = totalTime;
			}
		}
		public function onTick():void {
			checkCollision();
		}
		//public===============================================================
	
		//override===============================================================
		override public function checkCollision():void 
		{
			var len:int = this.collisionArr.length;
			var checkA:ICollisionAble;
			var checkB:ICollisionAble;
			var tempArr:Array=[];
			for (var i:int = 0; i <len-1 ; i++) 
			{
				checkA = collisionArr[i];
				for (var j:int = i + 1; j < len; j++ ) {
					checkB = collisionArr[j];
					//非同一阵营才让参与检测
					if ((checkA as IDisplayObject).type!=(checkB as IDisplayObject).type){
						if ((checkA as BaseDisplay).hitTestObject(checkB as BaseDisplay)) {
							tempArr.push(checkA);
							tempArr.push(checkB);
						}
					}
				}
			}
			
			var collisionNum:int=tempArr.length;
			for(var k:int;k<collisionNum;k++){
				(tempArr[k] as ICollisionAble).hasCollision();
			}
		}
	}
}
class Single{}